package com.trace.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;

/**
 * 安全配置类 - 完全禁用安全检查
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    /**
     * 安全过滤链配置 - 允许所有请求
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 禁用CSRF保护
        http.csrf().disable()
            // 启用跨域
            .cors().and()
            // 允许所有请求
            .authorizeRequests()
            .anyRequest().permitAll();
            
        return http.build();
    }
    
    /**
     * 配置跨域资源共享
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许所有源 - 这种写法可能会导致错误，因为同时设置了allowCredentials=true
        configuration.setAllowedOriginPatterns(Collections.singletonList("*"));
        // 允许所有HTTP方法
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        // 允许所有头信息
        configuration.setAllowedHeaders(Arrays.asList("*"));
        // 允许携带认证信息
        configuration.setAllowCredentials(true);
        // 预检请求的有效期，单位为秒
        configuration.setMaxAge(3600L);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有路径应用这个配置
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
} 